import { query } from '../../utils/db';

export default async function handler(req, res) {
  if (req.method === 'GET') {
    try {
      const { date } = req.query;
      const result = await query(
        'SELECT time_slot FROM appointments WHERE date = $1', 
        [date]
      );
      res.status(200).json(result.rows);
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  } else if (req.method === 'POST') {
    try {
      const { name, phone, date, time_slot, contact_method, notes } = req.body;
      
      // 验证必填字段
      if (!name || !phone || !date || !time_slot) {
        return res.status(400).json({ error: '缺少必填字段' });
      }
      
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(phone)) {
        return res.status(400).json({ error: '手机号格式不正确' });
      }
      
      // 检查该时间段是否已被预约
      const existing = await query(
        'SELECT id FROM appointments WHERE date = $1 AND time_slot = $2',
        [date, time_slot]
      );
      
      if (existing.rows.length > 0) {
        return res.status(400).json({ error: '该时间段已被预约' });
      }
      
      // 创建新预约
      const result = await query(
        `INSERT INTO appointments 
         (name, phone, date, time_slot, contact_method, notes) 
         VALUES ($1, $2, $3, $4, $5, $6) RETURNING *`,
        [name, phone, date, time_slot, contact_method, notes]
      );
      
      res.status(201).json(result.rows[0]);
    } catch (err) {
      res.status(500).json({ error: err.message });
    }
  } else {
    res.setHeader('Allow', ['GET', 'POST']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}